package org.whuims.io;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;

import org.apache.commons.io.FileUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.w3c.dom.ls.LSInput;

/**
 * 
 * @author Qiwang 2012-6-802:51:31
 */
public class XmlProcessor {

	public String generateXml(String filePath) {

		StringBuilder sb = new StringBuilder();
		sb.append("<parameters>\n<index>/home/qiwang/new_reuters_krovtz_index</index>\n<count>1000</count>\n");
		List<String> queryList = getQuerylist(filePath);
		int i = 101;
		for (String s : queryList) {
			sb.append("<query>\n<number>R").append(i)
					.append("</number>\n<text>").append(s)
					.append(")</text>\n</query>\n");
			i++;
		}
		sb.append("</text>\n<trecFormat>true</trecFormat>\n<queryOffset>1</queryOffset>\n<runID>run</runID>\n</parameters>");
		System.out.println(sb.toString());
		return sb.toString();

	}

	private List<String> getQuerylist(String filePath) {

		List<String> queryList = new ArrayList<String>();
		SAXReader reader = new SAXReader();
		Document document;
		try {
			document = reader.read(new File(filePath));
			List<Element> list = document
					.selectNodes("//parameters/query/text");
			Iterator iter = list.iterator();
			while (iter.hasNext()) {

				Element element = (Element) iter.next();
				// 得到#combine(Aid to handicapped people)
				String text = element.getText();
				//

				String[] strArr = text.split(" ");
				StringBuilder tempSb = new StringBuilder();
				for (String s : strArr) {
					if (s.endsWith(")")) {

						s = s.substring(0, s.indexOf(")"));

					}
					tempSb.append(s+ ".(tlevel0,tlevel1,tlevel2,tlevel3,tlevel4,tlevel5,tlevel6,tlevel7,tlevel8,blevel0,blevel1,blevel2,blevel3,blevel4,blevel5)");

				}
				System.out.println(tempSb.toString() + "\n");
				queryList.add(tempSb.toString());
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}

		return queryList;
	}

	public static StringBuffer addField(StringBuffer sb) {

		return sb;

	}
	
	public void writeXml(String storePath,String data){
		File storeFile = new File(storePath);
		if(!storeFile.exists())
			try {
				storeFile.createNewFile();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		try {
			FileUtils.writeStringToFile(storeFile, data);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	public static void main(String[] args) {

		String filePath = "resource/reuter_topics_dist.ini";
		// XmlReader.parse(filePath);
		XmlProcessor reader = new XmlProcessor();
		reader.generateXml(filePath);
	}
}
